<?php

namespace App\Http\Controllers\Backend;
use App\Exceptions\BusinessException;
use App\Common\Constant;
use App\Common\ResponseCode;
use App\Http\Controllers\BaseController;
use App\Http\Middleware\AdminAuth;
use App\Services\Base\FileService;
use App\Services\Base\KvService;
use App\Traits\VerifyRequestParam;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

/**
 * 文件上传控制器
 *
 * @package App\Http\Controllers\H5
 * @author WangBin
 * @date 2021-06/11
 */
class FileController extends BaseController
{
    use VerifyRequestParam;

    public function __construct()
    {
        $this->middleware(AdminAuth::class);
    }

    /**
     * 保存文件
     *
     * @param Request $request
     * @throws
     * @return
     */
    public function upload(Request $request)
    {
        // 文件类型 支持 图片 视频 音频
        $fileType = $this->verifyString('type');
        if(!key_exists($fileType, Constant::FILE_UPLOAD_TYPE_ALLOWED)) {
            throw new BusinessException(ResponseCode::FILE_TYPE_ERROR);
        }
        $file = $request->file('file');
        $validator = Validator::make([$fileType => $file], [$fileType => Constant::FILE_UPLOAD_TYPE_ALLOWED[$fileType]]);
        if($validator->fails()) {
            throw new BusinessException(ResponseCode::FILE_TYPE_ERROR);
        }
        $localPath = $file->store(Constant::FILE_UPLOAD_STORAGE_DIR[$fileType], 'public');
        $data = [
            'customize_name' => $file->getClientOriginalName(),
            'original_name' => $file->getClientOriginalName(),
            'storage_name' => pathinfo($localPath, PATHINFO_BASENAME),
            'extension' => pathinfo($localPath, PATHINFO_EXTENSION),
            'file_size' => $file->getSize(),
            'type' => $fileType,
            'relative_path' => Constant::FILE_URL_MEDIA . Constant::FILE_UPLOAD_STORAGE_DIR[$fileType] . '/'
        ];
        $ret = FileService::getInstance()->save($data);
        if($ret['file_id']) {
            return $this->success($ret);
        }
        return $this->fail(ResponseCode::FILE_UPLOAD_FAIL);
    }

    /**
     * 获取文件分组列表
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGroupList()
    {
        $ret = FileService::getInstance()->getGroupList();
        return $this->success($ret);
    }

    /**
     * 获取文件列表
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws BusinessException
     */
    public function getList()
    {
        $filter = [
            'group_id' => $this->verifyInteger('group_id', 1),
            'name' => $this->verifyString('name', ''),
            'limit' => $this->verifyInteger('limit', 20),
            'page' => $this->verifyInteger('page', 1) -1,
            'type' => $this->verifyString('type', '')
        ];
        $ret = FileService::getInstance()->getList($filter);
        return $this->success($ret);
    }
}